package com.edu.chapter07.network;

import androidx.annotation.NonNull;

import com.edu.chapter07.bean.User;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RetrofitNetworkHelper {
    public void fetchUser(ResponseCallback callback) {
        // 获取 API 实例
        ApiService apiService = RetrofitHelper.getApiService();

        // 发起异步请求
        Call<User> call = apiService.getUser();
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(@NonNull Call<User> call, @NonNull Response<User> response) {
                if (response.isSuccessful() && response.body() != null) {
                    callback.onSuccess(response.body()); // 返回解析好的 User 对象
                } else {
                    callback.onFailure("数据解析失败，状态码: " + response.code());
                }
            }

            @Override
            public void onFailure(@NonNull Call<User> call, Throwable t) {
                callback.onFailure("请求失败: " + t.getMessage());
            }
        });
    }

    // 回调接口（含错误处理）
    public interface ResponseCallback {
        void onSuccess(User user);
        void onFailure(String errorMsg); // 补充错误回调
    }
}